package com.atguigu.tingshu.account.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.atguigu.tingshu.account.mapper.RechargeInfoMapper;
import com.atguigu.tingshu.account.mapper.UserAccountMapper;
import com.atguigu.tingshu.account.service.RechargeInfoService;
import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.account.RechargeInfo;
import com.atguigu.tingshu.model.account.UserAccount;
import com.atguigu.tingshu.model.account.UserAccountDetail;
import com.atguigu.tingshu.vo.account.RechargeInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

@Service
@SuppressWarnings({"all"})
public class RechargeInfoServiceImpl extends ServiceImpl<RechargeInfoMapper, RechargeInfo> implements RechargeInfoService {

    @Autowired
    private RechargeInfoMapper rechargeInfoMapper;

    /**
     * 根据订单编号查询充值记录
     *
     * @param orderNo
     * @return
     */
    @Override
    public RechargeInfo getRechargeInfo(String orderNo) {
        LambdaQueryWrapper<RechargeInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RechargeInfo::getOrderNo, orderNo);
        return rechargeInfoMapper.selectOne(queryWrapper);
    }

    /**
     * 保存充值余额记录返回充值订单编号
     *
     * @param rechargeInfoVo
     * @param userId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, String> submitRecharge(RechargeInfoVo rechargeInfoVo, Long userId) {
        //1.构建充值记录对象
        RechargeInfo rechargeInfo = new RechargeInfo();
        rechargeInfo.setUserId(userId);
        //生成全局唯一充值订单编号
        String orderNo = "CZ" + DateUtil.today().replaceAll("-", "") + IdUtil.getSnowflakeNextId();
        rechargeInfo.setOrderNo(orderNo);
        rechargeInfo.setRechargeStatus(SystemConstant.ORDER_STATUS_UNPAID);
        rechargeInfo.setRechargeAmount(rechargeInfoVo.getAmount());
        rechargeInfo.setPayWay(rechargeInfoVo.getPayWay());
        this.save(rechargeInfo);
        //2.返回充值记录充值订单编号
        Map<String, String> map = new HashMap<>();
        map.put("orderNo", orderNo);
        return map;
    }

    @Autowired
    private UserAccountService userAccountService;

    /**
     * 在线付款成功后-更新充值状态&账户余额及新增账户变动日志
     *
     * @param orderNo
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void rechargePaySuccess(String orderNo) {
        //1.根据订单编号查询充值记录
        LambdaQueryWrapper<RechargeInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RechargeInfo::getOrderNo, orderNo);
        RechargeInfo rechargeInfo = this.getOne(queryWrapper);
        if (rechargeInfo != null) {
            //2.更新充值记录状态：支付成功
            rechargeInfo.setRechargeStatus(SystemConstant.ORDER_STATUS_PAID);
            this.updateById(rechargeInfo);

            //3.账户余额入账
            UserAccountMapper userAccountMapper = (UserAccountMapper) userAccountService.getBaseMapper();
            int count = userAccountMapper.add(rechargeInfo.getUserId(), rechargeInfo.getRechargeAmount());
            if (count == 0) {
                throw new GuiguException(500, "充值失败");
            }
            //4.新增账户变动日志
            userAccountService.saveUserAccountDetail(
                    rechargeInfo.getUserId(),
                    "充值：" + rechargeInfo.getRechargeAmount(),
                    SystemConstant.ACCOUNT_TRADE_TYPE_DEPOSIT,
                    rechargeInfo.getRechargeAmount(),
                    rechargeInfo.getOrderNo()
            );
        }
    }

    /**
     * 查询当前用户账户变动明细列表
     *
     * @param pageInfo
     * @param accountTradeTypeDeposit
     */
    @Override
    public void getUserAccountDetail(Page<UserAccountDetail> pageInfo, String accountTradeType) {
        rechargeInfoMapper.getUserAccountDetail(pageInfo, AuthContextHolder.getUserId(), accountTradeType);
    }
}
